package com.cheer.service.impl;

import com.cheer.entity.OaUserEntity;
import com.cheer.enums.LotteryActTypeEnum;
import com.cheer.exception.ServiceException;
import com.cheer.service.*;
import com.cheer.vo.FlowerVO;
import com.cheer.vo.UserFlowerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FlowerServiceImpl implements FlowerService {

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private OaUserService oaUserService;

    @Autowired
    private MallCategoryService mallCategoryService;

    @Autowired
    private IntegralConsumeService integralConsumeService;

    @Override
    public FlowerVO index(Integer userId) {

        FlowerVO flowerVO = new FlowerVO();
        OaUserEntity oaUserEntity = oaUserService.getById(userId);
        Integer intExchange = systemConfigService.getFlowerRadio();

        UserFlowerVO userFlowerVO = new UserFlowerVO()
                .setFlower(oaUserEntity.getFlower())
                .setShopIntegral(oaUserEntity.getShopCredit())
                .setMaxExchange(oaUserEntity.ableGetFlower(intExchange));
        // 鲜花数量
        flowerVO.setUserFlowerVO(userFlowerVO);
        flowerVO.setExchangeCredit(intExchange);

        // 获取小红花专区ID
        flowerVO.setCategoryId(mallCategoryService.getFlowerCatId());
        // 获取小红花兑换记录
        flowerVO.setExchangeRecords(integralConsumeService.listByUserId(userId));

        return flowerVO;
    }

    @Override
    public Integer getFlower(Integer userId) {

        OaUserEntity oaUserEntity = oaUserService.getById(userId);
        // 获取小红花比例
        Integer flowerRatio = systemConfigService.getFlowerRadio();

        return  oaUserEntity.ableGetFlower(flowerRatio);
    }

    @Override
    public void exchange(Integer userId, Integer exchangeNum) {

        if(exchangeNum == null || exchangeNum <= 0){
            throw new ServiceException(" 无效小红花数！");
        }
        Integer intExchange = systemConfigService.getIntExchange();
        Integer consumeIntegral = exchangeNum * intExchange;
        OaUserEntity oaUserEntity = oaUserService.getById(userId);
        Integer shopCredit = oaUserEntity.getShopCredit();
        if(shopCredit > consumeIntegral){
            // 执行兑换的记录
            integralConsumeService.save(userId, consumeIntegral, exchangeNum ,LotteryActTypeEnum.INTEGRAL);
            // 更新小红花数
            oaUserService.addFlower(userId, consumeIntegral, exchangeNum);
        }else{
            throw new ServiceException(" 剩余积分数不足！");
        }
    }

}
